"""
Utility function to validate correction issues and filter out false positives.
"""
from .call_llm import call_llm
import json
from .tools import format_json_response

def validate_issues(analysis_results):
    """
    Validate correction issues and filter out false positives.
    
    Args:
        analysis_results (dict): Dictionary with issue lists from analysis
        
    Returns:
        dict: Validated results with valid_issues and is_valid_json fields
    """
    # Initialize result
    result = {
        "valid_issues": [],
        "is_valid_json": True
    }
    
    # Collect all issues from analysis results
    all_issues = []
    for issue_type in ["typo_issues", "semantic_issues", "risk_level_issues", "compliance_status_issues"]:
        if issue_type in analysis_results:
            all_issues.extend(analysis_results[issue_type])
    
    # If no issues found, return empty result
    if not all_issues:
        return result
    
    # Create prompt for LLM to validate issues
    prompt = f"""
请审核以下AI检测出的问题，过滤掉可能的误报，并确保结果符合JSON格式要求。

问题列表：
{json.dumps(all_issues, ensure_ascii=False, indent=2)}

请以JSON格式返回审核结果，格式如下：
{{
  "valid_issues": [
    {{
      "type": "问题类型",
      "severity": "问题严重程度",
      "description": "问题描述",
      "suggestion": "改进建议",
      "title": "对应输入的title属性",
      "originalContent": "对应输入的inspector属性"
    }}
  ],
  "is_valid_json": true/false
}}

问题类型必须是以下之一：
- "typo"（错别字）
- "semantic"（语义混乱）
- "risk-level"（风险等级不合理）
- "compliance-status"（合规状态不合理）

问题严重程度必须是以下之一：
- "high"（高）
- "medium"（中）
- "low"（低）

请确保返回的是有效的JSON格式，且每个问题都包含所有必要的字段。
"""
    
    # Call LLM to validate issues
    response = call_llm(prompt)
    
    # Parse the response
    try:
        response = format_json_response(response)   
        validated = json.loads(response)
        # Ensure the result has the expected structure
        if "valid_issues" in validated and isinstance(validated["valid_issues"], list):
            # Ensure each issue has title and originalContent
            for issue in validated["valid_issues"]:
                if "title" not in issue or not issue["title"]:
                    # Find the original issue to get the title
                    for orig_issue in all_issues:
                        if orig_issue.get("type") == issue.get("type") and \
                           orig_issue.get("description") == issue.get("description"):
                            issue["title"] = orig_issue.get("title", "")
                            break
                
                if "originalContent" not in issue or not issue["originalContent"]:
                    # Find the original issue to get the originalContent
                    for orig_issue in all_issues:
                        if orig_issue.get("type") == issue.get("type") and \
                           orig_issue.get("description") == issue.get("description"):
                            issue["originalContent"] = orig_issue.get("originalContent", "")
                            break
            
            result["valid_issues"] = validated["valid_issues"]
        if "is_valid_json" in validated and isinstance(validated["is_valid_json"], bool):
            result["is_valid_json"] = validated["is_valid_json"]
    except json.JSONDecodeError:
        # If LLM response is not valid JSON, return original issues but mark as invalid
        result["valid_issues"] = all_issues
        result["is_valid_json"] = False
    
    return result

if __name__ == "__main__":
    # Test with sample issues
    test_issues = {
        "typo_issues": [
            {
                "type": "typo",
                "severity": "medium",
                "description": "错别字：'宇'应为'字'",
                "suggestion": "将'错别宇'修改为'错别字'",
                "title": "测试标题",
                "originalContent": "这是一个测试文本，包含一些错别宇和语意混乱的内容。"
            }
        ],
        "semantic_issues": [
            {
                "type": "semantic",
                "severity": "high",
                "description": "语义混乱：描述不清晰",
                "suggestion": "重新组织语言，使表达更加清晰",
                "title": "测试标题",
                "originalContent": "这是一个测试文本，包含一些错别宇和语意混乱的内容。"
            }
        ]
    }
    
    result = validate_issues(test_issues)
    print(json.dumps(result, ensure_ascii=False, indent=2))
